package com.mach.platform.sprider.opc;

import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.*;

import java.util.concurrent.Executors;

public class MuOpcTest {

    public static void main(String[] args){
        // create connection information
        final ConnectionInformation ci = new ConnectionInformation();
//        ci.setHost("OPCServer.WinCC.1");
        ci.setHost("192.168.1.10");
        ci.setDomain("");
        ci.setUser("administrator");
        ci.setPassword("123-abc");
        ci.setProgId("OPCServer.WinCC.1");
        //ci.setClsid("OPCServer.WinCC.1");
        // ci.setClsid("680DFBF7-C92D-484D-84BE-06DC3DECCD68"); // if ProgId is not working, try it using the Clsid instead
        final String itemId = "34_G103_Prot_Yc";
        // create a new server
        System.out.println("start new Server...");
        final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());

        System.out.println("new Server...success");
        try {
            // connect to server
            System.out.println("server connect...");
            server.connect();
            System.out.println("server connect...success");
            // add sync access, poll every 500 ms
            final AccessBase access = new SyncAccess(server, 500);
            access.addItem(itemId, new DataCallback() {
                @Override
                public void changed(Item item, ItemState state) {
                    System.out.println("state=" + state);
                }
            });
            // start reading
            access.bind();
            // wait a little bit
            Thread.sleep(10 * 1000);
            // stop reading
            access.unbind();
        } catch (final JIException e) {
            System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

